/* eslint-disable no-promise-executor-return */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomerTable from "@/components/CustomerTable";
import DictTag from "@/components/DictTag";
import { CloudDownloadOutlined, DeleteOutlined, ExclamationCircleFilled, PlusOutlined } from "@ant-design/icons";
import { ActionType, PageContainer, ProColumns } from "@ant-design/pro-components";
import { Button, Divider, FormInstance, Input, Modal, Popconfirm, Space, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import ConfigForm, { ConfigFormData } from "./components/ConfigForm";
import { getDict } from "@/services/api/module/system/dict";
import { getPageList, remove, save, update } from "@/services/api/module/message/config";
import FilterDrawer from "@/components/FilterDrawer";
import { createTableColumns, pagination, tableTab } from "./constants";
import { loadNamespaces } from "i18next";
const { confirm } = Modal;
import { dict } from "@/utils/DictionaryCacheManager";

const MessageConfig: React.FC = () => {
	const formTableRef = useRef<FormInstance>();
	const [open, setOpen] = useState<boolean>(false);
	const [dataSource, setDataSource] = useState<API.System.MessageConfigVO | undefined>(undefined);
	const [formOpen, setFormOpen] = useState<boolean>(false);
	const [menuVisible, setMenuVisible] = useState<boolean>(false);
	const actionRef = useRef<ActionType>();
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [selectedRows, setSelectedRows] = useState<API.System.MessageConfigVO[]>([]);
	const [statusOptions, setStatusOptions] = useState<any>([]);
	const [supplierTypeOptions, setSupplierTypeOptions] = useState<any>([]);
	const [configType, setConfigType] = useState<any>([]);
	const [tabKey, setTabKey] = useState<React.Key>("SMS");
	const [tabParam, setTabParam] = useState<{ type: any }>({ type: "SMS" });
	useEffect(() => {
		dict.getDict("sys_normal_disable").then(data => {
			setStatusOptions(data);
		});
		dict.getDict("sys_message_config_type").then(data => {
			setConfigType(data);
		});
		dict.getDict("sys_message_supplier_type").then(data => {
			setSupplierTypeOptions(data);
		});
	}, []);
	const handleColumnEditor = (record: API.System.MessageConfigVO) => {
		setFormOpen(true);
		setCurrentId(record?.id);
	};
	const handleColumnRemove = (record: API.System.MessageConfigVO) => {
		handleRemove(record?.id as number);
	};

	const columns = createTableColumns(statusOptions, supplierTypeOptions, handleColumnEditor, handleColumnRemove);
	// 删除
	const handleRemove = async (ids: number | Array<number | undefined>) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number | undefined>, names: Array<string>) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: `确认删除配置名称为：${names} 的配置文件吗?`,
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};

	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setFormOpen(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};

	// 保存
	const handleSave = async (values: ConfigFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as ConfigFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 編輯
	const handleUpdate = async (values: ConfigFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as ConfigFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};

	const [searchFormValue, setSearchFormValue] = useState<any>(undefined);
	const [searchValue, setSearchValue] = useState<any>(undefined);
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		return await getPageList({ ...searchFormValue, ...searchValue, type: tabKey }).then((data: any) => {
			return data;
		});
	};
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			loadNamespaces: value
		});
		actionRef.current?.reload();
	};
	const handleFormCancel = () => {
		setFormOpen(false);
		setCurrentId(undefined);
	};
	return (
		<>
			<CustomerTable<API.System.MessageConfigVO>
				actionRef={actionRef}
				headerTitle="消息配置"
				rowKey="id"
				key="messageConfig"
				search={false}
				toolbar={{
					search: (
						<Space>
							<Input.Search placeholder="消息配置名称搜索" allowClear style={{ width: 250 }} onSearch={handleOnSearch} />
							<FilterDrawer
								columns={columns}
								tableActionRef={actionRef}
								onReset={() => {
									setSearchFormValue(undefined);
									actionRef?.current?.reload();
								}}
								onSubmit={(values: any) => {
									setSearchFormValue(values);
									actionRef?.current?.reload();
								}}
							/>
						</Space>
					),
					menu: {
						type: "tab",
						activeKey: tabKey,
						items: tableTab,
						onChange: key => {
							setTabParam({ type: key });
							setTabKey(key as React.Key);
							actionRef.current?.reload();
						}
					}
				}}
				pagination={pagination}
				request={tableDataRequest}
				// @ts-ignore
				toolBarRender={() => {
					return (
						<>
							<Button
								type="primary"
								key="add"
								onClick={async () => {
									setFormOpen(true);
								}}
							>
								<PlusOutlined /> 添加配置
							</Button>
							{selectedRows?.length !== 0 && (
								<Button
									type="primary"
									key="remove"
									danger
									onClick={async () => {
										showRemoveConfirm(
											Array.from(selectedRows, ({ id }) => id),
											Array.from(selectedRows, ({ name }) => name)
										);
									}}
								>
									<DeleteOutlined />
									批量删除
								</Button>
							)}
						</>
					);
				}}
				columns={columns}
				rowSelection={{
					onChange: (_, selectedRows) => {
						setSelectedRows(selectedRows);
					}
				}}
				tableAlertRender={false}
			/>
			<ConfigForm
				statusOptions={statusOptions}
				open={formOpen}
				configType={configType}
				supplierTypeOptions={supplierTypeOptions}
				onSubmit={async (values: ConfigFormData) => {
					return values.id ? await handleUpdate(values) : await handleSave(values);
				}}
				onCancel={handleFormCancel}
				id={currentId}
			/>
		</>
	);
};

export default MessageConfig;
